package com.zhixing.service.processor;

import com.zhixing.model.SwaggerDefinitionModelAttr;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * swagger 响应 json 解析处理器
 * @author zhixing
 */
public class SwaggerResponseModelAttrsProcessor implements SwaggerProcessor{
    /** json 解析后的 入参对象 **/
    @Getter
    private SwaggerDefinitionModelAttr              result;

    @Getter
    private Map<String, Object>                     responseObj;

    @Getter
    private Map<String, SwaggerDefinitionModelAttr> definitionMap;



    private SwaggerResponseModelAttrsProcessor(){
        this.result = new SwaggerDefinitionModelAttr();
    }

    public static Builder createBuild(){
        return  new Builder();
    }

    public static class Builder{
        private SwaggerResponseModelAttrsProcessor processor;
        public Builder(){
            this.processor = new SwaggerResponseModelAttrsProcessor();
        }

        public Builder responseObj(Map<String, Object> responseObj){
            this.processor.responseObj = responseObj;
            return this;
        }

        public Builder definitinMap(Map<String, SwaggerDefinitionModelAttr> definitinMap){
            this.processor.definitionMap = definitinMap;
            return this;
        }

        public SwaggerResponseModelAttrsProcessor build(){
            return this.processor;
        }

    }

    @Override
    public SwaggerResponseModelAttrsProcessor process() throws IOException {
        doProcess();
        return this;
    }

    /**
     * 处理请求参数列表
     *
     * @return
     */
    private void doProcess() throws IOException{
        Map<String, Object> schema = (Map<String, Object>) responseObj.get("schema");
        String type = (String) schema.get("type");

        String ref = null;
        //数组
        if ("array".equals(type)) {
            Map<String, Object> items = (Map<String, Object>) schema.get("items");
            if (items != null && items.get("$ref") != null) {
                ref = (String) items.get("$ref");
            }
        }
        //对象
        if (schema.get("$ref") != null) {
            ref = (String) schema.get("$ref");
        }

        //其他类型
        result.setType(StringUtils.defaultIfBlank(type, StringUtils.EMPTY));

        if (StringUtils.isNotBlank(ref) && definitionMap.get(ref) != null) {
            result = definitionMap.get(ref);
        }
    }
}
